package com.laiqilin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.laiqilin.entity.Classes;
import com.laiqilin.entity.Student;
import com.laiqilin.mapper.ClassesMapper;
import com.laiqilin.mapper.StudentMapper;
import com.laiqilin.service.StudentService;
import com.laiqilin.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ClassesMapper classesMapper;

	@Override
	public List<Student> findAll() {
		List<Student> students = studentMapper.selectByExample(null);
		if (students == null) {
			students = new ArrayList<>();  // 防止为 null
		}

		students.forEach(st -> {
			if (st.getCid() != null) {
				Classes classes = classesMapper.selectByPrimaryKey(st.getCid());
				if (classes != null) {
					st.setCname(classes.getCname());
				} else {
					// 处理 classes 为 null 的情况
					st.setCname("未知班级");
				}
			} else {
				// 处理 cid 为 null 的情况
				st.setCname("未知班级");
			}
		});

		return students;
	}


	// 分页查询
	@Override
	public PageResult<Student> findByPage(Integer page, Integer pageSize) {	
		PageHelper.startPage(page,pageSize);		
		List<Student> students = this.findAll();		
		Page<Student> studentPage = (Page<Student>) students;
		return new PageResult<>(studentPage.getResult(),studentPage.getTotal());

	}
}
